package com.itheima;

import java.awt.*;

public class Ground {
    private boolean gameOver = false;
    private int[][] obstacles = new int[Global.WIDTH][Global.HEIGHT];

    public void accept(Shape shape) {
        System.out.println("Ground's accept shape");
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                if (shape.isMember(x, y, false)) {
                    obstacles[shape.getLeft() + x][shape.getTop() + y] = 1;
                }
            }
        }
        deleteFullLine();
        isGameOver();
    }

    public void isGameOver() {
        for (int x = 0; x < Global.WIDTH; x++) {
            if (obstacles[x][0] != 0) {
                gameOver = true;
            }
        }
    }

    public void deleteFullLine() {
        for (int y = Global.HEIGHT - 1; y > 0; y--) {
            boolean full = true;
            for (int x = 0; x < Global.WIDTH; x++) {
                if (obstacles[x][y] != 1)
                    full = false;
            }
            if (full) {
                deleteLine(y);
            }
        }
    }

    public void deleteLine(int numLine) {
        for (int y = numLine; y > 0; y--) {
            for (int x = 0; x < Global.WIDTH; x++) {
                obstacles[x][y] = obstacles[x][y - 1];
            }
        }
        for (int x = 0; x < Global.WIDTH; x++) {
            obstacles[x][0] = 0;
        }
    }

    public void drawMe(Graphics g) {
        g.setColor(Color.ORANGE);
        for (int y = 0; y < Global.HEIGHT; y++) {
            for (int x = 0; x < Global.WIDTH; x++) {
                if (obstacles[x][y] == 1) {
                    g.fill3DRect(x * Global.CELL_SIZE, y * Global.CELL_SIZE, Global.CELL_SIZE, Global.CELL_SIZE, true);
                }
            }
        }
        g.setColor(Color.red);
        Font font = new Font("宋体", Font.BOLD, 100);
        g.setFont(font);
        if (gameOver) {
            g.drawString("gameover", 0, 300);
        }
        System.out.println("Ground's drawMe");
    }

    public boolean isMoveable(Shape shape, int action) {
        int left = shape.getLeft();
        int top = shape.getTop();
        switch (action) {
            case Shape.LEFT:
                left--;
                break;
            case Shape.RIGHT:
                left++;
                break;
            case Shape.DOWN:
                top++;
                break;
        }
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                if (shape.isMember(x, y, action == Shape.ROTATE)) {
                    if (top + y >= Global.HEIGHT ||
                            left + x < 0 ||
                            left + x >= Global.WIDTH ||
                            obstacles[x + left][y + top] == 1)
                        return false;
                }
            }
        }
        return true;
    }
}
